package com.bhs.sansonglogistics.ui.enterprise;

import static com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity.RC_LOCATION;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.bean.LocationBean;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.StatusBarUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 选择位置
 */
public class LocationSelectionActivity extends BaseActivity implements AMap.OnMyLocationChangeListener, PoiSearch.OnPoiSearchListener, View.OnClickListener, GeocodeSearch.OnGeocodeSearchListener {

    private MapView mMapView = null;
    //初始化地图控制器对象
    private AMap aMap;
    private RecyclerView rvList;
    private BaseQuickAdapter<LocationBean, BaseViewHolder> adapter;
    private MyLocationStyle myLocationStyle;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    private String city;
    private EditText etSearch;
    private boolean isChangeCenterPoint;

    @Override
    public int initLayout() {
        return R.layout.activity_location_selection;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        city = getIntent().getStringExtra("city");
        StatusBarUtil.setTranslucentStatus(this, true);

        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        findViewById(R.id.tv_cancel).setOnClickListener(this);
        findViewById(R.id.btn_accomplish).setOnClickListener(this);

        rvList = findViewById(R.id.rv_list);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }


        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        //连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。
        // （1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。 只定位一次
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.interval(2000);
        //设置定位蓝点的Style
        aMap.setMyLocationStyle(myLocationStyle);
        //设置默认定位按钮是否显示，非必需设置。
        aMap.getUiSettings().setMyLocationButtonEnabled(true);
        // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.setMyLocationEnabled(true);
        aMap.setOnMyLocationChangeListener(this);
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setMyLocationButtonEnabled(false); //显示默认的定位按钮
        //设置希望展示的地图缩放级别
        aMap.animateCamera(CameraUpdateFactory.zoomTo(17));
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        adapter = new BaseQuickAdapter<LocationBean, BaseViewHolder>(R.layout.item_address, mList) {

            @Override
            protected void convert(BaseViewHolder helper, LocationBean item) {
                helper.setText(R.id.tv_name, item.getName());
                helper.setText(R.id.tv_address, item.getAddress());
                helper.setText(R.id.tv_distance, item.getDistance());
                helper.setGone(R.id.tv_distance, !item.getDistance().equals("-1m"));
                helper.setGone(R.id.decollator, !item.getDistance().equals("-1m"));
                helper.setGone(R.id.iv_tick, item.isTick());
            }
        };
        rvList.setAdapter(adapter);
        rvList.setLayoutManager(new LinearLayoutManager(this));

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (LocationBean locationBean : mList) {
                    locationBean.setTick(false);
                }
                mList.get(position).setTick(true);
                adapter.notifyDataSetChanged();
            }
        });

        etSearch = findViewById(R.id.et_search);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                PoiSearch(s.toString());
            }
        });
    }

    private PoiSearch poiSearch;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    private final List<LocationBean> mList = new ArrayList();

    private double latitude;
    private double longitude;
    private GeocodeSearch geocoderSearch;

    @Override
    public void onMyLocationChange(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        if (TextUtils.isEmpty(city)) {
            PoiSearch("");
            try {
                geocoderSearch = new GeocodeSearch(this);
            } catch (AMapException e) {
                throw new RuntimeException(e);
            }
            geocoderSearch.setOnGeocodeSearchListener(this);
            LatLonPoint latLonPoint = new LatLonPoint(latitude, longitude);
            // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
            RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
            geocoderSearch.getFromLocationAsyn(query);
        } else {
            isChangeCenterPoint = true;
            PoiSearch(city);
        }


    }

    private void PoiSearch(String keyWord) {
        //poi搜索条件
        //keyWord表示搜索字符串，
        //第二个参数表示POI搜索类型，二者选填其一，选用POI搜索类型时建议填写类型代码，码表可以参考下方（而非文字）
        //cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
        PoiSearch.Query query = new PoiSearch.Query(keyWord, "", city);
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(1);//设置查询页码
        try {
            poiSearch = new PoiSearch(this, query);
        } catch (AMapException e) {
            e.printStackTrace();
        }
        poiSearch.setOnPoiSearchListener(this);

        if (TextUtils.isEmpty(keyWord)) {
            poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(latitude,
                    longitude), 1000));//设置周边搜索的中心点以及半径
        }
        poiSearch.searchPOIAsyn();
    }


    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        mList.clear();
        for (PoiItem pois : poiResult.getPois()) {
            mList.add(new LocationBean(pois.getTitle(), pois.getSnippet(), pois.getDistance() + "m",
                    pois.getLatLonPoint().getLatitude(), pois.getLatLonPoint().getLongitude(),
                    pois.getAdName(), pois.getCityName(), pois.getProvinceName()));
        }
        if (isChangeCenterPoint) {
            CameraUpdate update = CameraUpdateFactory.newCameraPosition(
                    new CameraPosition(new LatLng(mList.get(0).getLatitude(), mList.get(0).getLongitude()), 12, 30, 30));
            aMap.moveCamera(update);
        }
        mList.get(0).setTick(true);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onClick(View v) {
        MyUtils.hideSoftInputWindow(mActivity, etSearch);
        if (v.getId() == R.id.btn_accomplish) {
            for (LocationBean locationBean : mList) {
                if (locationBean.isTick()) {
                    Intent i = new Intent();
                    i.putExtra("name", locationBean.getName());
                    i.putExtra("address", locationBean.getAddress());
                    i.putExtra("latitude", locationBean.getLatitude());
                    i.putExtra("longitude", locationBean.getLongitude());
                    i.putExtra("county", locationBean.getCounty());
                    i.putExtra("city", locationBean.getCity());
                    i.putExtra("province", locationBean.getProvince());
                    setResult(3, i);
                    finish();
                    break;
                }
            }
        } else {
            finish();
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        city = regeocodeResult.getRegeocodeAddress().getCity();
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
}